import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { PrismaClient } from '@prisma/client';

import { genCode } from '../../utils/genCode';

import * as crypto from 'node:crypto';

@Injectable()
export class UserService {
  constructor(private prisma: PrismaClient) {}
  async create(createUserDto: CreateUserDto) {
    const data = createUserDto;
    const hash = crypto.createHash('md5');
    data.password = hash.update(data.password).digest('hex');
    data.code = genCode();
    const res = await this.prisma.user.create({ data });
    console.log('res11', res);
    return res;
  }

  findAll(query) {
    return this.prisma.user.findMany({
      select: { username: true, code: true, password: false },
      take: +query.pageSize,
      skip: (+query.pageNum - 1) * query.pageSize,
    });
  }

  findOne(data: any) {
    return this.prisma.user.findUnique({ where: data });
  }

  async update(id: number, updateUserDto) {
    const profile = await this.prisma.profile.findUnique({
      where: { userId: id },
    });
    const select = {
      username: true,
      code: true,
      profile: true,
      password: false,
    };
    if (profile) {
      return this.prisma.user.update({
        where: { id },
        data: {
          profile: {
            update: updateUserDto.profile,
          },
        },
        select,
      });
    } else {
      return this.prisma.user.update({
        where: { id },
        data: {
          profile: {
            create: Object.assign({}, updateUserDto.profile, { userId: id }),
          },
        },
        select,
      });
    }
  }

  remove(id: number) {
    return this.prisma.user.delete({
      where: { id },
    });
  }
}
